<template>
  <el-table :data="tableData" stripe height="100%">
    <el-table-column
      v-for="column in tableColumns"
      :key="column.code"
      :prop="column.code"
      :label="column.name"
      :width="column.width ? column.width : 100"
      :formatter="
        (row, column, cellValue, index) => {
          return cell_formatter(column, cellValue, tableColumns)
        }
      "
    />
    <el-table-column width="200" label="操作">
      <template #default="scope">
        <el-button
          type="primary"
          :disabled="scope.row.order_qty - scope.row.arrived_qty === 0"
          size="small"
          @click="show_arrive_win(scope.row)"
          >收货</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="show_arrive" :show-close="false" width="350px">
    <el-input-number :controls="false" style="margin-right: 10px" v-model="arriveNum" />
    <el-button type="primary" @click="arrive()"> 确认 </el-button>
  </el-dialog>
</template>

<script lang="ts" setup>
import { stock_order_define } from '@/meta/index'
import type { stock_order } from '@/types/billdata'
import { fill_ref_info, cell_formatter } from '@/utils/common'
import { onMounted, ref } from 'vue'
import { useDbStore } from '@/stores/modules/database'
import { e_stock_order_status } from '@/types/enum'
import { order_to_arrive } from '@/utils/converter'
import { useRouter } from 'vue-router'
import { reserv_from_order_to_arrive } from '@/utils/reservHelper'
const route = useRouter()
const dbStore = useDbStore()
const arriveNum = ref<number>()
const show_arrive = ref<boolean>()
const currentStockOrder = ref<stock_order>()
const tableColumns = stock_order_define
const tableData = ref<stock_order[]>()
onMounted(() => {
  const tmp = dbStore.stockorder
  fill_ref_info(tmp, stock_order_define)
    .then(() => {
      tableData.value = tmp
    })
    .catch(() => {
      console.log('err')
    })
})
const show_arrive_win = (p: stock_order) => {
  currentStockOrder.value = p
  arriveNum.value = currentStockOrder.value!.order_qty - currentStockOrder.value!.arrived_qty
  show_arrive.value = true
}
const arrive = () => {
  show_arrive.value = false
  currentStockOrder.value!.arrived_qty = arriveNum.value!
  const arrive = order_to_arrive(currentStockOrder.value!, arriveNum.value!)
  useDbStore().addArriveCode(arrive)
  if (currentStockOrder.value!.arrived_qty > 0) {
    if (currentStockOrder.value!.arrived_qty === currentStockOrder.value!.order_qty) {
      currentStockOrder.value!.status = e_stock_order_status.全部到货
    } else {
      currentStockOrder.value!.status = e_stock_order_status.部分到货
    }
  }
  dbStore.saveStockInBill(tableData.value)
  reserv_from_order_to_arrive(currentStockOrder.value!, arrive)
  route.push({ path: 'arriveList' })
}
</script>
